import requests
import pickle



#如果没有song_name,就让song_name=[]，如果存在，就将内容读取出来
try:
    with open('song_name.txt', 'rb')as f:
        try:
            song_name = pickle.load(f)
        except:
            song_name = []
except:
    fp = open("song_name.txt", "x")
    fp.close()
    song_name = []

# 获取歌曲信息
def get_songinfo(songname):
    # 请求的api
    url = f"https://music.163.com/api/cloudsearch/get/web?hlpretag=<span class=\\\"s-fc7\\\">&hlposttag=</span>&s={songname}&type=1"
    response = requests.get(url)
    # 将数据转换为json格式
    data = response.json()
    songinfo = {"id": int(data['result']['songs'][0]['id']), "name": data['result']['songs'][0]['name'],
                "songer": data['result']['songs'][0]['ar'][0]['name']}
    return songinfo

# 获取下载地址
def down_url(id):
    # 请求下载歌曲的url
    url = f"https://music.163.com//api/song/enhance/player/url/v1?encodeType=flac&ids=[{id}]&level=lossless"
    response = requests.get(url)
    data = response.json()
    # 得到下载mp3的url
    mp3_url = data['data'][0]['url']
    return mp3_url

# 下载音乐
def downMusic(url):
    mp3_name = songinfo['name'] + ".mp3"
    # 将音乐名称添加至list
    song_name.append(mp3_name)
    with open("song_name.txt", 'wb')as f:
        pickle.dump(song_name, f)

    with open(mp3_name, "wb") as file:
        music = requests.get(url)  # 获取解析到的数据
        file.write(music.content)  # 把数据写入缓冲区文件
        file.flush()  # 把数据存入缓冲区
        file.close()  # 关闭文件


while 1:
    try:
        songname = input("请输入歌曲名称:")
        songinfo = get_songinfo(songname)
        mp3_url = down_url(songinfo['id'])
        downMusic(mp3_url)
    except:
        print("该歌曲为付费歌曲")


